package com.pan.annotation.aspect;

import com.pan.annotation.CouponCheck;
import com.pan.entity.Coupon;
import com.pan.entity.Result;
import com.pan.excep.error.AspectException;
import com.pan.feign.CouponFeign;
import com.pan.tools.ArrayTools;
import com.pan.tools.RedisTools;
import com.pan.vo.UserCouponShowVo;
import io.swagger.models.auth.In;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.lang.reflect.Method;
import java.util.List;

@Aspect
@Component
public class CouponCheckAspect {

    @Resource
    private RedisTools redisTools;

    @Resource
    private CouponFeign couponFeign;

    @Pointcut("@annotation(com.pan.annotation.CouponCheck)")
    public void annotationCut(){}

    @Before("annotationCut()")
    public void couponCheck(JoinPoint joinPoint){
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        Method targetMethod = methodSignature.getMethod();
        CouponCheck couponCheck = targetMethod.getAnnotation(CouponCheck.class);
        String ticketName = couponCheck.ticketName();
        String idName = couponCheck.CouponHistoryIdName();
        Object[] args = joinPoint.getArgs();
        String[] parameterNames =  methodSignature.getParameterNames();
        Integer ticketIndex = ArrayTools.indexOf(parameterNames,ticketName);
        Integer idIndex = ArrayTools.indexOf(parameterNames,idName);
        String ticket = (String) args[ticketIndex];
        Long id = (Long) args[idIndex];
        Long userId = Long.parseLong((String) redisTools.hget("user:"+ticket,"id").getData());
        Result<Boolean> isUserResult = couponFeign.isUserCoupon(userId,id);
        if (!isUserResult.getData()){
            throw new AspectException(403,"该优惠券不属于该用户",CouponCheck.class,targetMethod);
        }

    }

}
